import { alovaInstance } from '@/utils/request'
import {
  Task,
  CreateTaskRequest,
  UpdateTaskRequest,
  TaskListResponse,
  MyDayTasksResponse,
  TaskLog,
  CreateTaskLogRequest
} from '@/types'
import { API_PATHS, API_CONFIG } from '@/configs'

// 任务相关API

/**
 * 获取任务列表
 * @param params 查询参数
 * @returns 任务列表
 */
export const getTasks = async (params?: {
  group_id?: number
  status?: number
  is_important?: boolean
  is_my_day?: boolean
  page?: number
  page_size?: number
}) => {
  const method = alovaInstance.Get<TaskListResponse>(
    `${API_CONFIG.PREFIX}/${API_CONFIG.VERSION}${API_PATHS.TASK.LIST}`,
    { params }
  )
  return await method.send()
}

/**
 * 创建任务
 * @param data 任务创建请求数据
 * @returns 创建的任务
 */
export const createTask = async (data: CreateTaskRequest) => {
  const method = alovaInstance.Post<Task>(
    `${API_CONFIG.PREFIX}/${API_CONFIG.VERSION}${API_PATHS.TASK.CREATE}`,
    data
  )
  return await method.send()
}

/**
 * 获取任务详情
 * @param id 任务ID
 * @returns 任务详情
 */
export const getTaskDetail = async (id: number) => {
  const method = alovaInstance.Get<Task>(
    `${API_CONFIG.PREFIX}/${API_CONFIG.VERSION}${API_PATHS.TASK.DETAIL(id)}`
  )
  return await method.send()
}

/**
 * 更新任务
 * @param id 任务ID
 * @param data 任务更新请求数据
 * @returns 更新后的任务
 */
export const updateTask = async (id: number, data: UpdateTaskRequest) => {
  const method = alovaInstance.Put<Task>(
    `${API_CONFIG.PREFIX}/${API_CONFIG.VERSION}${API_PATHS.TASK.UPDATE(id)}`,
    data
  )
  return await method.send()
}

/**
 * 删除任务
 * @param id 任务ID
 * @returns 删除结果
 */
export const deleteTask = async (id: number) => {
  const method = alovaInstance.Delete(
    `${API_CONFIG.PREFIX}/${API_CONFIG.VERSION}${API_PATHS.TASK.DELETE(id)}`
  )
  return await method.send()
}

/**
 * 更新任务分组
 * @param id 任务ID
 * @param group_id 新的分组ID
 * @returns 更新结果
 */
export const updateTaskGroup = async (id: number, group_id: number) => {
  const method = alovaInstance.Put(
    `${API_CONFIG.PREFIX}/${API_CONFIG.VERSION}${API_PATHS.TASK.UPDATE_GROUP(id)}`,
    { group_id }
  )
  return await method.send()
}

/**
 * 获取"我的一天"任务列表
 * @returns "我的一天"任务列表
 */
export const getMyDayTasks = async () => {
  const method = alovaInstance.Get<MyDayTasksResponse>(
    `${API_CONFIG.PREFIX}/${API_CONFIG.VERSION}${API_PATHS.TASK.MY_DAY}`
  )
  return await method.send()
}

/**
 * 获取任务日志列表
 * @param taskId 任务ID
 * @returns 任务日志列表
 */
export const getTaskLogs = async (taskId: number) => {
  const method = alovaInstance.Get<TaskLog[]>(
    `${API_CONFIG.PREFIX}/${API_CONFIG.VERSION}${API_PATHS.LOG.LIST(taskId)}`
  )
  return await method.send()
}

/**
 * 添加任务日志
 * @param taskId 任务ID
 * @param data 日志创建请求数据
 * @returns 创建的日志
 */
export const createTaskLog = async (taskId: number, data: CreateTaskLogRequest) => {
  const method = alovaInstance.Post<TaskLog>(
    `${API_CONFIG.PREFIX}/${API_CONFIG.VERSION}${API_PATHS.LOG.CREATE(taskId)}`,
    data
  )
  return await method.send()
}
